package me.zhengjie.minbearwcs.serivce.mission.processor.outbound;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.minbearwcs.dao.mission.inf.WcsMissionDao;
import me.zhengjie.minbearwcs.dao.outbound.inf.OutboundStockUpRecordDao;
import me.zhengjie.minbearwcs.dao.outbound.inf.OutboundStockUpRecordHistoryDao;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.AgvActionSource;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.AgvTaskSource;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.actionEnum.AgvAction;
import me.zhengjie.minbearwcs.entity.DTO.transfer.Tuple;
import me.zhengjie.minbearwcs.entity.PO.agv.missionEnum.AgvMissionType;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.WcsMission;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.status.OutboundStockUpMissionStatus;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.type.MissionType;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.history.OutboundStockUpRecordHistory;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.stockUp.OutboundStockUpRecord;
import me.zhengjie.minbearwcs.resource.WcsResource;
import me.zhengjie.minbearwcs.serivce.agv.task.agvTask.AgvTaskDispatcher;
import me.zhengjie.minbearwcs.serivce.mission.processor.MissionProcessor;
import me.zhengjie.minbearwcs.serivce.mission.processor.MissionProcessorCommonUtil;
import me.zhengjie.minbearwcs.serivce.mission.storageProcessor.locker.Floor5Or6.Storage5Or6FloorPassSelector;
import me.zhengjie.minbearwcs.utils.IdWorker;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;


@Slf4j
@Component
@RequiredArgsConstructor
public class OutboundStockUpMissionProcessor implements MissionProcessor {


    private final AgvTaskDispatcher getPutTaskDispatcher;
    private final TransactionTemplate transactionTemplate;
    private final WcsMissionDao wcsMissionDao;
    private final WcsResource wcsResource;
    private final IdWorker idWorker;
    private final MissionProcessorCommonUtil commonUtil;
    private final OutboundStockUpRecordDao outboundStockUpRecordDao;
    private final OutboundStockUpRecordHistoryDao outboundStockUpRecordHistoryDao;
    private final Storage5Or6FloorPassSelector storage5Or6FloorPassSelector;


    private final Object lock = new Object();

    @Override
    public MissionType getMissionType() {
        return MissionType.OUTBOUND_STOCK_UP;
    }

    @Override
    public void process(WcsMission missionInfo) {
        OutboundStockUpMissionStatus missionStatus = (OutboundStockUpMissionStatus) missionInfo.getEnumMissionStatus();

        switch (missionStatus) {
            case WAIT_FOR_DISPATCH:
                dispatchAgvTask(missionInfo);
                break;
            case DISPATCHING:
                break;
            case PROCESSING:
                monitorMission(missionInfo);
                break;
            case FINISH:
                finishWcsMission(missionInfo);
                break;
            case CANCEL:
                break;
        }
    }

    public OutboundStockUpRecord getOutboundStockUpDetail(String stockUpId) {
        return outboundStockUpRecordDao.selectByStockUpId(stockUpId);
    }


    public boolean statusChangeDISPATCHING(Integer missionId) {
        if (OutboundStockUpMissionStatus.WAIT_FOR_DISPATCH == wcsMissionDao.selectMissionStatusById(missionId)) {
            synchronized (lock) {
                if (OutboundStockUpMissionStatus.WAIT_FOR_DISPATCH == wcsMissionDao.selectMissionStatusById(missionId)) {
                    return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
                        try {
                            wcsMissionDao.updateMissionStatusById(missionId, OutboundStockUpMissionStatus.DISPATCHING.name());
                            wcsMissionDao.updateStartTime(missionId, LocalDateTime.now());
                            return true;
                        } catch (Exception e) {
                            log.error("wcs任务状态转换出错", e);
                            status.setRollbackOnly();
                        }
                        return false;
                    }));
                }
            }
        }

        return false;
    }


    public void dispatchAgvTask(WcsMission missionInfo) {
        if (!statusChangeDISPATCHING(missionInfo.getId())) return;

        OutboundStockUpRecord orderDetail = getOutboundStockUpDetail(missionInfo.getAssociatedDetailId());


        wcsResource.getExecutor().execute(() -> {
            Boolean executeRes = transactionTemplate.execute(status -> {
                try {
                    Tuple<String> start = storage5Or6FloorPassSelector.selectPass(orderDetail.getStartSmallStorage());
                    Tuple<String> end = storage5Or6FloorPassSelector.selectPass(orderDetail.getDestinationSmallStorage());

                    String agvTaskId = "Task_Agv_" + idWorker.nextId();
                    AgvTaskSource agvTaskSource = new AgvTaskSource(agvTaskId, AgvMissionType.OUTBOUND_TYPE, 1, missionInfo.getMissionId(), missionInfo.getMissionType(),
                            OutboundStockUpMissionStatus.PROCESSING.name(), orderDetail.getPalletCode(), start.value, end.value);
                    agvTaskSource.addAction(new AgvActionSource(orderDetail.getStartSmallStorage(), AgvAction.GET))
                            .addAction(new AgvActionSource(orderDetail.getDestinationSmallStorage(), AgvAction.PUT));


                    if (getPutTaskDispatcher.dispatch(agvTaskSource)) {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), OutboundStockUpMissionStatus.PROCESSING.name());
                    } else {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), OutboundStockUpMissionStatus.WAIT_FOR_DISPATCH.name());
                    }
                    return true;
                } catch (Exception e) {
                    log.error("wcs任务：{}，生成agv任务失败", missionInfo.getMissionId(), e);
                    status.setRollbackOnly();
                }
                return false;
            });

            if (Boolean.FALSE.equals(executeRes)) {
                wcsMissionDao.updateMissionStatusById(missionInfo.getId(), OutboundStockUpMissionStatus.WAIT_FOR_DISPATCH.name());
            }

        });
    }


    public void monitorMission(WcsMission missionInfo) {

    }

    public void finishWcsMission(WcsMission missionInfo) {
        transactionTemplate.executeWithoutResult(status -> {
            try {
                OutboundStockUpRecord orderDetail = getOutboundStockUpDetail(missionInfo.getAssociatedDetailId());
                if (orderDetail.getOutboundOrderCode() == null) {
                    outboundStockUpRecordHistoryDao.insert(
                            new OutboundStockUpRecordHistory(null, orderDetail.getStockUpId(), orderDetail.getOutboundOrderCode(), orderDetail.getOutboundOrderDetailId(),
                                    orderDetail.getPalletCode(), orderDetail.getMaterialCode(), orderDetail.getMaterialNum(), orderDetail.getStartFloorNum(),
                                    orderDetail.getStartSmallStorage(), orderDetail.getDestinationFloorNum(), orderDetail.getDestinationSmallStorage(), orderDetail.getCreateTime())
                    );
                    outboundStockUpRecordDao.deleteById(orderDetail.getId());
                }

                missionInfo.setFinishTime(LocalDateTime.now());
                commonUtil.transformMissionHistory(missionInfo);
            } catch (Exception e) {
                log.error("任务结束错误", e);
                status.setRollbackOnly();
            }
        });

    }


}
